package com.demo.shardingsphere.user.config;


import com.demo.shardingsphere.util.SpringContextUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.sql.SQLException;
import java.util.Collection;

/**
 * 数据库路由
 */
public class UserDatabaseAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * 用户id 分库
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames,
                             PreciseShardingValue<Long> shardingValue) {
        Long value = shardingValue.getValue()  ;
        String dbName= null;
        try {
            //数据库名字
            dbName = SpringContextUtils.getShardingService().getDb(value);
        } catch (SQLException e) {

            throw new RuntimeException("dbName error",e);
        }
        return dbName;

    }
}
